import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/pages/test_detail/model/model_test_detail.dart';
import 'package:flutter_base/pages/test_questions/test_questions_logic.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class ColorPsychologyWidget extends StatefulWidget {
  final TestQuestionsLogic logic;

  const ColorPsychologyWidget({
    super.key,
    required this.logic,
  });

  @override
  State<ColorPsychologyWidget> createState() => _ColorPsychologyWidgetState();
}

class _ColorPsychologyWidgetState extends State<ColorPsychologyWidget> {
  final ScrollController _scrollController = ScrollController();
  double _scrollOffset = 0.0;

  // 选中索引
  int? _selectedIndex;

  final List<Color> rowGradients = [
    // 第1行 - 黄色系渐变
    const Color(0xFFFFFAE8),
    const Color(0xFFFFF8DE),
    const Color(0xFFFFF6D9),
    const Color(0xFFFFF4D3),
    const Color(0xFFFFF3CA),
    const Color(0xFFFFF2C5),
    const Color(0xFFFFF0BE),
    const Color(0xFFFFECB0),
    // 第2行 - 橙色系渐变
    const Color(0xFFFCF4E8),
    const Color(0xFFFCEFDF),
    const Color(0xFFFCEAD9),
    const Color(0xFFFAE8D2),
    const Color(0xFFFAE2C8),
    const Color(0xFFFAE0C5),
    const Color(0xFFF9DCBC),
    const Color(0xFFF9D6B2),
    // 第3行 - 粉色系渐变
    const Color(0xFFFBE8E8),
    const Color(0xFFFAE2DF),
    const Color(0xFFF9DDD9),
    const Color(0xFFF9D5CF),
    const Color(0xFFF7CFC8),
    const Color(0xFFF6C9C2),
    const Color(0xFFF5C2BB),
    const Color(0xFFF4B4AB),
    // 第4行 - 紫粉色系渐变
    const Color(0xFFFBE8F0),
    const Color(0xFFF9DEEA),
    const Color(0xFFF8D9E6),
    const Color(0xFFF7D0E1),
    const Color(0xFFF5C8DD),
    const Color(0xFFF4C2D8),
    const Color(0xFFF3BBD3),
    const Color(0xFFF1AFCC),
    // 第5行 - 紫色系渐变
    const Color(0xFFFAE8FD),
    const Color(0xFFF8DEFC),
    const Color(0xFFF7D8FB),
    const Color(0xFFF7D0FB),
    const Color(0xFFF6CBFA),
    const Color(0xFFF5C2F9),
    const Color(0xFFF4BBF9),
    const Color(0xFFF2AEF8),
    // 第6行 - 淡紫色系渐变
    const Color(0xFFF0E8FC),
    const Color(0xFFEBDEFC),
    const Color(0xFFE5D8FC),
    const Color(0xFFDFD0FC),
    const Color(0xFFDDCBFC),
    const Color(0xFFD8C2FC),
    const Color(0xFFD2BBFC),
    const Color(0xFFC6AEF7),
    // 第7行 - 蓝紫色系渐变
    const Color(0xFFE8E8FC),
    const Color(0xFFDFDEFC),
    const Color(0xFFDBD8FC),
    const Color(0xFFD5D0FA),
    const Color(0xFFCFCBFA),
    const Color(0xFFC7C2FA),
    const Color(0xFFC0BBFA),
    const Color(0xFFB6AEF9),
    // 第8行 - 蓝色系渐变
    const Color(0xFFE8F0FC),
    const Color(0xFFDEEBFC),
    const Color(0xFFD8E8FC),
    const Color(0xFFD0E3FC),
    const Color(0xFFCBDEFC),
    const Color(0xFFC2DBFC),
    const Color(0xFFBBD7FC),
    const Color(0xFFAECFFC),

    const Color(0xFFE8F2FC),
    const Color(0xFFDEEEFC),
    const Color(0xFFD8EBFC),
    const Color(0xFFD0E8FC),
    const Color(0xFFCBE4FC),
    const Color(0xFFC2E1FC),
    const Color(0xFFBBDEFC),
    const Color(0xFFAED7FC),

    const Color(0xFFE8F8FC),
    const Color(0xFFDEF5FC),
    const Color(0xFFD8F2FC),
    const Color(0xFFD0EFFC),
    const Color(0xFFCBECFC),
    const Color(0xFFC2E9FC),
    const Color(0xFFBBE6FC),
    const Color(0xFFAEE0FC)
  ];

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      setState(() {
        _scrollOffset = _scrollController.offset;
      });
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<TestQuestionsLogic>(builder: (logic) {
      // 更新选中索引
      int questionId = logic.currentQuestion?.id ?? 0;
      _selectedIndex = logic.userAnswers[questionId]?.isNotEmpty == true
          ? logic.userAnswers[questionId]?.first
          : null;

      return Stack(
        // clipBehavior: Clip.none, // 允许子组件超出Stack边界
        children: [
          // GridView在底层
          GridView.builder(
              controller: _scrollController,
              // scrollDirection: BouncingScrollPhysics(),
              physics: const BouncingScrollPhysics(),
              padding: EdgeInsets.symmetric(horizontal: 24.w),
              itemCount: rowGradients.length,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 8,
                mainAxisSpacing: 3,
                crossAxisSpacing: 3,
              ),
              itemBuilder: (context, index) {
                int questionId = logic.currentQuestion?.id ?? 0;
                // bool isSelect =
                //     logic.userAnswers[questionId]?.contains(index) == true;

                return GestureDetector(
                  onTap: () {
                    logic.userAnswers[questionId] = [index + 1];
                    logic.update();
                  },
                  child: Container(
                    color: rowGradients[index],
                  ),
                );
              }),

          // 选中项的放大方块在上层
          if (_selectedIndex != null)
            _buildSelectedOverlay(_selectedIndex! - 1, logic),
        ],
      );
    });
  }

  Widget _buildSelectedOverlay(int selectedIndex, TestQuestionsLogic logic) {
    // 计算选中项的位置
    int row = selectedIndex ~/ 8;
    int col = selectedIndex % 8;

    // 计算选中项的位置偏移
    double gridItemWidth = (1.sw - 48.w - 21) / 8;
    double gridItemHeight = gridItemWidth; // 假设网格是正方形

    // 计算放大方块的位置，考虑滚动偏移
    // 计算item的中心位置
    double itemCenterX = 24.w + col * (gridItemWidth + 3) + gridItemWidth / 2;
    double itemCenterY =
        row * (gridItemHeight + 3) + gridItemHeight / 2 - _scrollOffset;

    // 标准放大方块的大小
    double overlaySize = 76.w;

    // 检查是否超出父组件边界并调整大小
    double topEdge = itemCenterY - overlaySize / 2;
    double bottomEdge = itemCenterY + overlaySize / 2;
    double adjustedSize = overlaySize;
    double adjustedTop = itemCenterY - overlaySize / 2;

    // 如果顶部超出视图
    if (topEdge < 0) {
      double overflow = -topEdge;
      adjustedSize = overlaySize - overflow;
      adjustedTop = 0;
    }

    // 如果底部超出视图
    double viewportHeight = MediaQuery.of(context).size.height;
    if (bottomEdge > viewportHeight) {
      double overflow = bottomEdge - viewportHeight;
      adjustedSize = overlaySize - overflow;
    }

    return Positioned(
      // 放大方块居中于选中的item
      left: itemCenterX - overlaySize / 2,
      top: adjustedTop,
      child: Material(
        elevation: 8, // 添加阴影提高视觉层级
        color: Colors.transparent,
        child: Container(
          width: max(overlaySize, 0),
          height: max(adjustedSize, 0),
          decoration: BoxDecoration(
            color: rowGradients[selectedIndex],
            boxShadow: [
              BoxShadow(
                color: AppColor.color24A4B3.withOpacity(0.32),
                blurRadius: 22.w,
                spreadRadius: 0,
                offset: const Offset(0, 8),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
